package com.mymvc.controller.upload;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: UploadController
 * Package: com.mymvc.controller.upload
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/9 21:07
 * @Version 1.0
 */

@Controller
public class UploadController {
    //转接用的,WEB-INF下的不能通过网页直接访问(http://localhost:8080/springmvc02/uploadFile
    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile uploadFile, HttpServletRequest request) {
        //1.做非空判断
        if (uploadFile!=null&& !StringUtils.isEmpty(uploadFile.getOriginalFilename())) {
            //1.获取上传文件的名称(例如上传1.txt=>返回的文件名1.txt)
            String originalFilename = uploadFile.getOriginalFilename();
            //2.解决上传文件重名问题:将文件名替换成uuid值,保证文件名唯一
            // 1.txt=> uuid值.txt
            String uuid = UUID.randomUUID().toString().replace("-", "");

            //3.获取原文件的扩展名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

            //4.将uuid值和扩展名拼接得到唯一文件名
            String newFilename = uuid + extension;

            //5.将上传的文件写入到服务端硬盘
            //request.getServletContext().getRealPath("/") 获取部署应用的根路径
            try {
                uploadFile.transferTo(new File(request.getServletContext().getRealPath("/"),newFilename));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "success";
    }
}
